<template>
    <div class="production-plan">
        <!-- 修改按钮点击事件 -->
        <el-button type="primary" @click="saveAll">修改计划和明细</el-button>
        <el-button type="primary" @click="GetPackagingPlanlist">查看包装计划</el-button>
        <h3 class="title">包装计划</h3>
        <!-- 基本信息 -->
        <el-form :model="formData" :rules="rules" label-width="120px" ref="formRef">
            <el-row :gutter="20">
                <el-col :span="7">
                  <el-form-item label="计划类型" prop="planType">
                    <el-select
                      v-model="formData.planType"
                      clearable
                      placeholder="请选择"
                      style="width: 240px"
                    >
                      <el-option label="包装计划" value="1" />
                      <el-option label="过滤计划" value="2" />
                      <el-option label="生产计划" value="3" />
                      <el-option label="其他计划" value="4" />
                    </el-select>
                  </el-form-item>
              </el-col>
                <el-col :span="7">
                    <el-form-item label="计划日期" prop="scheduledDates">
                        <el-date-picker
                            v-model="formData.scheduledDates"
                            type="date"
                            readonly
                            required
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="包装规格" prop="packingSpecifications">
                        <el-input v-model="formData.packingSpecifications"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="包装形式" prop="packagingForm">
                        <el-input v-model="formData.packagingForm"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="产品系列" prop="productRange">
                        <el-input v-model="formData.productRange"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="计划产量" prop="plannedProduction">
                        <el-input-number
                            v-model.number="formData.plannedProduction"
                            :min="0"
                        ></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="产量单位" prop="productionUnits">
                        <el-input v-model="formData.productionUnits"></el-input>
                    </el-form-item>
                </el-col>
                
                <el-col :span="12">
                    <el-form-item label="备注 " prop="remark">
                        <el-input v-model="formData.remark" type="textarea" rows="3" required></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 计划明细 -->
        <div class="detail-section">
            <h7 class="sub-title">计划明细</h7>
            <el-button size="small" @click="addNewRow">新增行</el-button>
            <el-table :data="planDetailsList" border style="width: 100%">
              <!-- 车间名称下拉框 -->
              <el-table-column label="车间名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.workshopName"
                          :options="workshopOptions"
                          :value-key="workshopValueKey"
                          placeholder="请选择车间名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in workshopOptions"
                        :key="item.workshopId"
                        :label="item.workshopName"
                        :value="item.workshopId"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <!-- 工段名称下拉框 -->
              <el-table-column label="工段名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.workSectionName"
                          :options="workSectionOptions"
                          :value-key="workSectionValueKey"
                          placeholder="请选择工段名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in workSectionOptions"
                        :key="item.workSectionId"
                        :label="item.workSectionName"
                        :value="item.workSectionId"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <!-- 产线名称下拉框 -->
              <el-table-column label="产线名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.productionLineName"
                          :options="productionLineOptions"
                          :value-key="productionLineValueKey"
                          placeholder="请选择产线名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in productionLineOptions"
                        :key="item.productionLineId"
                        :label="item.productionLineName"
                        :value="item.productionLineId"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <!-- 设备名称下拉框 -->
              <el-table-column label="设备名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.deviceName"
                          :options="deviceOptions"
                          :value-key="deviceValueKey"
                          placeholder="请选择设备名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in deviceOptions"
                        :key="item.id"
                        :label="item.equipment_Name"
                        :value="item.id"
                      />
                    </el-select>
                  </template>
              </el-table-column>
                <el-table-column label="开始日期" width="280px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.friDate"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="结束日期" width="280px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.endDate"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="负责人" width="180px">
                  <template #default="{ row }">
                <el-input
                  v-model="row.leader"
                  :disabled="row.productInfoFilled"
                  required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openOurRepresentativesDialog">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
                  </template>
              </el-table-column>
                <el-table-column label="人员数量" width="180px">
                    <template #default="{ row }">
                        <el-input-number
                            v-model.number="row.personnelNumber"
                            :min="0"
                        ></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180px">
                    <template #default="{ row }">
                        <el-button size="small" type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 负责人选择对话框 -->
      <el-dialog
        v-model="ourRepresentativesDialogVisible"
        width="500px"
        title="负责人选择"
        append-to-body
      >
        <el-table
          :data="ourRepresentativesList"
          highlight-current-row
          border
          size="small"
          @current-change="handleOurRepresentativesChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="userName" label="代表姓名" />
          <el-table-column property="depmentName" label="部门" />
          <el-table-column property="roleName" label="职位" />
        </el-table>
        <template #footer>
          <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
        </template>
      </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { read, write } from '@/axios/axiosHelper';
import { useCounterStore } from '@/stores/counter';
import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();
const store = useCounterStore();

const formRef = ref(null);

// 主表单数据
const formData = reactive({
    preparation: true,
    picking: true,
    planType:'',
    packagingPlanId: route.query.packagingPlanId,
    scheduledDates: new Date(),
    packingSpecifications: "",
    packagingForm: "",
    productRange: "",
    plannedProduction: 0,
    productionUnits: "",
    isload: 0,
    remark: ""
});

// 主表单验证规则
const rules = reactive({
    scheduledDates: [
        { required: true, message: '计划日期不能为空', trigger: 'blur' }
    ],
    plannedProduction: [
        { type: 'number', required: true, message: '计划产量必须为数字且不能为空', trigger: 'blur' }
    ],
    materialRequirementsBill: [
        { required: true, message: '物料需求清单不能为空', trigger: 'blur' }
    ],
    remark: [
        { required: true, message: '备注不能为空', trigger: 'blur' }
    ]
});

// 车间、工段、产线、设备选项
const workshopOptions = ref([
      "workshopId" ,
      "workshopName"
]);
const workSectionOptions = ref([
      "workSectionId",
      "workSectionName"
]);
const productionLineOptions = ref([
      "productionLineId",
      "productionLineName"
]);
const deviceOptions = ref([
      "id",
      "equipment_Name",
      "model",
      "manufacturer",
      "purchase_Date",
      "status"
]);

// 获取车间选项数据
const fetchWorkshopOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/Workshop/Handle')
    .then(res => {
          workshopOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取车间选项数据失败:', error);
          ElMessage.error('获取车间选项数据失败，请检查网络或联系管理员');
      });
};

// 获取工段选项数据
const fetchWorkSectionOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/WorkSection/Handle')
    .then(res => {
          workSectionOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取工段选项数据失败:', error);
          ElMessage.error('获取工段选项数据失败，请检查网络或联系管理员');
      });
};

// 获取产线选项数据
const fetchProductionLineOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/ProductionLine/Handle')
    .then(res => {
          productionLineOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取产线选项数据失败:', error);
          ElMessage.error('获取产线选项数据失败，请检查网络或联系管理员');
      });
};

// 获取设备选项数据
const fetchDeviceOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/Equipment/GetEquipment')
    .then(res => {
          deviceOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取设备选项数据失败:', error);
          ElMessage.error('获取设备选项数据失败，请检查网络或联系管理员');
      });
};

onMounted(() => {
  fetchWorkshopOptions();

  fetchWorkSectionOptions();
  fetchProductionLineOptions();
  fetchDeviceOptions();
});


// 明细数据列表
const planDetailsList = ref([]);



// 统一错误处理函数
const handleError = (error, message) => {
    console.error(message, error);
    ElMessage.error(`${message}，请检查网络或联系管理员`);
};



// 获取基本信息
const GetOutsourcingBYId = async () => {
    try {
        const response = await axios.get(`http://8.154.44.176:8000/p2-read/api/PackagingPlan/GetBYIdPackagingPlan`, {
            params: {
                PackagingPlanId: route.query.packagingPlanId
            }
        });
        const responseData = response.data.data[0];
        responseData.scheduledDates = new Date(responseData.scheduledDates);
        Object.assign(formData, responseData);
    } catch (error) {
        handleError(error, '获取主表信息失败');
    }
};

// 获取明细信息
const GetOutsourcingDeatilBYId = async () => {
    try {
        const response = await axios.get(`http://8.154.44.176:8000/p2-read/api/PackagingPlan/GetBYIdPackagingPlanDetails`, {
            params: {
                PackagingPlanId: route.query.packagingPlanId
            }
        });
        planDetailsList.value = response.data.data.map(item => ({
            ...item,
            friDate: item.friDate ? new Date(item.friDate) : null,
            endDate: item.endDate ? new Date(item.endDate) : null,
            packagingPlanId: item.packagingPlanId || formData.packagingPlanId,
            isSaved: true,
            productInfoFilled: item.productInfoFilled || false
        }));
    } catch (error) {
        handleError(error, '获取明细表信息失败');
    }
};

onMounted(async () => {
    const packagingPlanId = route.query.packagingPlanId;
    if (!packagingPlanId) {
        ElMessage.error('缺少必要的计划ID参数');
        return;
    }
    await GetOutsourcingBYId();
    await GetOutsourcingDeatilBYId();
});


// 修改主表单和明细
const saveAll = async () => {
    if (formRef.value) {
        const isValid = await formRef.value.validate();
        if (isValid) {
            try {
                // 修改主表单
                const response = await axios.post(`http://8.154.44.176:8000/p2-write/api/PackagingPlan/UpdatePackagingPlan`, formData);
                if (response.data.code === 200) {
                    console.log('表主键', formData.packagingPlanId);
                    ElMessage.success('主表单修改成功');

                    // 更新明细表的外键
                    const updatedDetails = planDetailsList.value.map(row => ({
                        ...row,
                        packagingPlanId: formData.packagingPlanId
                    }));

                    // 修改明细
                    const saveDetailPromises = updatedDetails.map(async (row) => {
                        try {
                            const detailResponse = await axios.post(
                                `http://8.154.44.176:8000/p2-write/api/PackagingPlan/UpdatePackagingPlanDetails`,
                                row
                            );
                            if (detailResponse.data.code === 200) {
                                row.isSaved = true;
                                return true;
                            } else {
                                ElMessage.error(`明细修改失败：${detailResponse.data.message}`);
                                return false;
                            }
                        } catch (detailError) {
                            handleError(detailError, `保存明细项时出错，数据：${JSON.stringify(row)}`);
                            return false;
                        }
                    });

                    const results = await Promise.all(saveDetailPromises);
                    if (results.every(result => result)) {
                        ElMessage.success('所有明细修改成功');
                    }
                } else {
                    ElMessage.error(`主表单修改失败：${response.data.message}`);
                }
            } catch (error) {
                handleError(error, '修改过程中发生错误');
            }
        }
    }
};

// 新增行
const addNewRow = () => {
    planDetailsList.value.push({
        workshopName: "",
        workSectionName: "",
        productionLineName: "",
        deviceName: "",
        friDate: null,
        endDate: null,
        leader: "",
        personnelNumber: 0,
        packagingPlanId: formData.packagingPlanId,
        isSaved: false,
        productInfoFilled: false
    });
};

// 删除单条明细
const deleteDetail = (row) => {
    ElMessageBox.confirm('确认删除该条明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = planDetailsList.value.indexOf(row);
        if (index !== -1) {
            planDetailsList.value.splice(index, 1);
            ElMessage.success('明细删除成功');
        }
    }).catch(() => {
        ElMessage.info('取消删除');
    });
};

// 日期验证函数
const checkDateOrder = (row) => {
    const { friDate, endDate } = row;
    if (friDate && endDate && new Date(friDate) > new Date(endDate)) {
        ElMessage.error('结束日期不能小于开始日期');
        row.endDate = null;
    }
};

// 跳转包装计划列表
const GetPackagingPlanlist = () => {
    router.push('GetPackagingPlanlistView');
};
</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section {
    width: 100%;
}

.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}

.el-input[readonly],
.el-date-editor[readonly],
.el-input-number[disabled] {
    background-color: #f5f7fa;
    cursor: not-allowed;
}
</style>    